package com.honglu.backend.common.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.aliyun.oss.OSSClient;
import com.honglu.utils.OSSUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;

import com.honglu.backend.common.Constants;
import com.honglu.utils.PropertiesUtil;
import com.honglu.utils.UUIDUtils;
 
 
 

/**
 * 公用方法
 * @author xiajiyun
 *
 */
public class BaseController {
	
	private static Logger logger=Logger.getLogger(BaseController.class);
	
	
	/**
	 * 图片上传，相对路劲
	 * @param request
	 * @param response
	 * @param file
	 * @return
	 */
	public String uploadFiles(HttpServletRequest request,HttpServletResponse response, MultipartFile file){
		try {
			String ip = PropertiesUtil.get("ip");// 获取地址
			//System.out.println(System.getProperty("user.dir"));
			if(StringUtils.isNotEmpty(ip)){
				if("localhostPic".equals(ip)){// 本地
					String filetimes = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); // 时间戳
					String filePathDir = Constants.FILEPATH + "/" + filetimes;
					String fileRealPathDir = request.getSession().getServletContext().getRealPath(filePathDir); // 获取本地存储路径
					File fileSaveFile = new File(fileRealPathDir);
					if (!fileSaveFile.exists()){
						fileSaveFile.mkdirs();
					}
					OutputStream outputStream = null;
					String str = "";
					String type="";
					String fileName=file.getOriginalFilename();
					type=fileName.indexOf(".")!=-1?fileName.substring(fileName.lastIndexOf(".")+1, fileName.length()):null;
					String getFileName = UUIDUtils.getUUID() + "." + type; // 本地生成的图片名称
					if (null != file) {
						if( null != type  && "GIF".equals(type.toUpperCase())||"PNG".equals(type.toUpperCase())||"JPG".equals(type.toUpperCase())){// 非空, // 判断图片类型
							str = "/" + filePathDir + "/" + getFileName;
						}else{
							return "error";
						}
						
						File files = new File(request.getSession().getServletContext().getRealPath("/") + str); // 新建一个文件
						try {
							outputStream = new FileOutputStream(files);
							outputStream.write(file.getBytes());
							outputStream.flush();
						} catch (Exception e) {
							e.printStackTrace();
						} finally {
								try {
									outputStream.close();
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
						}
						
						// 注释的这2行，适应在tomcat环境下用
//						String hostProperties=get("name");
//						return hostProperties + str; 
						
						// 本地存储路劲
						/*return "../../.." + str;*/
						return PropertiesUtil.get("name") + str;
					} 
				}else if("picture".equals(ip)){// 测试库和生产库
					String filetimes = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); // 时间戳
					String filePathDir =Constants.PICTURE +"/"+ filetimes; //存
					String fileRealPathDir = request.getSession().getServletContext().getRealPath(filePathDir); // 获取本地存储路径
					File fileSaveFile = new File(fileRealPathDir);
					if (!fileSaveFile.exists()){
						fileSaveFile.mkdirs();
					}
					
					OutputStream outputStream = null;
					String str = "";
					String picNmae= ""; //图片名字
					String type="";
					String fileName = file.getOriginalFilename();
					
					if (null != file) {
						type = fileName.indexOf(".")!=-1?fileName.substring(fileName.lastIndexOf(".")+1, fileName.length()):null;
						if( null != type  && "GIF".equals(type.toUpperCase())||"PNG".equals(type.toUpperCase())||"JPG".equals(type.toUpperCase())){// 非空, // 判断图片类型
							picNmae = "/" + filePathDir +"/"+ UUIDUtils.getUUID() + "." + type;
						}else{
							return "error";
						}

						File files = new File(request.getSession().getServletContext().getRealPath("/") + picNmae); // 新建一个文件
						try {
							outputStream = new FileOutputStream(files);
							outputStream.write(file.getBytes());
							outputStream.flush();
						} catch (Exception e) {
							e.printStackTrace();
						} finally {
								try {
									outputStream.close();
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
						}
						//System.out.println("/" + systemCenter + "/" + picNmae);
						return  PropertiesUtil.get("name") + picNmae;
					} 
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		
		return "";
	}
	
	
	/**
	 * oss图片上传，相对路劲
	 * @param file
	 * @return
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 */


	public String uploadFilesOss(MultipartFile file, String fileNamePath) throws FileNotFoundException, IOException {
	
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		String dateFolder = df.format(new Date());
		//获取oss 链接
		OSSClient ossClient = OSSUtil.getOSSClient();
		//获取上传图片全名称
		String fileName = file.getOriginalFilename();
		//获取上传图片格式
		String type = fileName.indexOf(".")!=-1?fileName.substring(fileName.lastIndexOf(".")+1, fileName.length()):null;
		//重新生成图片名称
		String imageName = UUIDUtils.getUUID() + "." + type;
		//重新生成图片名称
		String imageNamePath = fileNamePath +"/" + dateFolder;
		if (null != file) {
			if( null != type  && "GIF".equals(type.toUpperCase())||"PNG".equals(type.toUpperCase())||"JPG".equals(type.toUpperCase())){// 非空, // 判断图片类型
				//上传图片
				boolean flag = OSSUtil.uploadInputStreamObject2OSS(ossClient, file.getInputStream(), imageName, PropertiesUtil.get("file.bucket"), imageNamePath);
				if (flag) {
					return PropertiesUtil.get("file.url")+"/"+imageNamePath +"/" +imageName;
				}	
			}else{
				return "error";
			}
			
		} 
		 
		return "error";

	}



}
